"""
模拟Gemini视频分类器

基于模拟Gemini服务的视频内容分类器，用于测试和演示。
"""

import time
from typing import Dict, List, Any
from datetime import datetime
import logging

from src.core.di import Injectable, Inject
from src.modules.scanners.base import FileInfo, FileType, FileCategory
from src.services.mock_gemini_service import MockGeminiService
from .base import AIClassifier, ClassificationResult


@Injectable(scope="singleton")
class MockGeminiVideoClassifier(AIClassifier):
    """
    模拟Gemini视频分类器
    
    使用模拟Gemini服务进行视频内容分析和分类，用于测试和演示。
    """
    
    def __init__(self,
                 mock_gemini_service: MockGeminiService = Inject(MockGeminiService),
                 config: Dict[str, Any] = Inject("config"),
                 logger: logging.Logger = Inject("logger")):
        self.mock_gemini_service = mock_gemini_service
        self.config = config
        self.logger = logger
        
        # AI分类器配置
        self.ai_config = config.get("ai_classifier", {})
        self.confidence_threshold = self.ai_config.get("confidence_threshold", 0.7)
        self.max_frames = self.ai_config.get("max_frames_per_video", 5)
    
    @property
    def name(self) -> str:
        return "mock_gemini_video_classifier"
    
    @property
    def version(self) -> str:
        return "1.0.0-mock"
    
    @property
    def supported_file_types(self) -> List[str]:
        return ["video", "mp4", "avi", "mov", "mkv", "webm"]
    
    def is_available(self) -> bool:
        """检查分类器是否可用"""
        return self.mock_gemini_service.is_available()
    
    async def classify(self, file_info: FileInfo, **kwargs) -> ClassificationResult:
        """分类视频文件"""
        start_time = time.time()
        
        # 检查文件类型
        if file_info.file_type != FileType.VIDEO:
            return ClassificationResult(
                success=False,
                error=f"不支持的文件类型: {file_info.file_type.value}",
                classifier_type=self.name,
                timestamp=datetime.now()
            )
        
        try:
            self.logger.info(f"使用模拟Gemini分析视频: {file_info.name}")
            
            # 调用模拟Gemini服务分析视频
            analysis_result = await self.mock_gemini_service.analyze_video_content(
                file_info.path,
                max_frames=kwargs.get("max_frames", self.max_frames)
            )
            
            processing_time = time.time() - start_time
            
            if not analysis_result.get("success", False):
                return ClassificationResult(
                    success=False,
                    error=analysis_result.get("error", "模拟AI分析失败"),
                    classifier_type=self.name,
                    processing_time=processing_time,
                    timestamp=datetime.now()
                )
            
            # 解析分类结果
            category_str = analysis_result.get("category", "unclassified")
            confidence = analysis_result.get("confidence", 0.0)
            reasoning = analysis_result.get("reasoning", "")
            features = analysis_result.get("features", [])
            
            # 转换分类字符串为枚举
            try:
                category = FileCategory(category_str)
            except ValueError:
                self.logger.warning(f"未知的分类类型: {category_str}")
                category = FileCategory.UNCLASSIFIED
            
            # 创建分类结果
            result = ClassificationResult(
                category=category,
                confidence=confidence,
                reasoning=reasoning,
                features=features,
                classifier_type=self.name,
                model_name=self.mock_gemini_service.model_name,
                processing_time=processing_time,
                timestamp=datetime.now(),
                raw_response=analysis_result.get("raw_response", ""),
                metadata={
                    "frames_analyzed": analysis_result.get("frames_analyzed", 0),
                    "gemini_model": self.mock_gemini_service.model_name,
                    "api_version": "mock-v1",
                    "is_mock": True
                },
                success=True
            )
            
            self.logger.info(
                f"模拟Gemini分类完成: {file_info.name} -> {category.value} "
                f"(置信度: {confidence:.2f}, 耗时: {processing_time:.2f}s)"
            )
            
            return result
            
        except Exception as e:
            processing_time = time.time() - start_time
            error_msg = f"模拟Gemini分类失败: {e}"
            self.logger.error(error_msg)
            
            return ClassificationResult(
                success=False,
                error=error_msg,
                classifier_type=self.name,
                processing_time=processing_time,
                timestamp=datetime.now()
            )
